package com.cqhz.quwan.ui.main.fragment


import android.content.Intent
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.*
import com.cqhz.quwan.model.news.NewsBannerBean
import com.cqhz.quwan.model.news.NewsBaseBean
import com.cqhz.quwan.model.news.NewsInfoBean
import com.cqhz.quwan.model.news.NewsMatchBean
import com.cqhz.quwan.mvp.news.NewsContract
import com.cqhz.quwan.mvp.news.NewsPresenter
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.base.AbsFragment
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.activity.MyPredictionActivity
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.main.adapter.NewsMixAdapter
import com.cqhz.quwan.ui.main.match.MatchAnalysisActivity
import com.cqhz.quwan.ui.main.order.OrderListActivity
import com.cqhz.quwan.ui.widget.dialog.PrizeDialog
import com.cqhz.quwan.ui.widget.dialog.RewardDialog
import com.cqhz.quwan.util.UmengAnalyticsHelper
import com.cqhz.quwan.util.run4false
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.fragment_news.*
import me.militch.quickcore.core.HasDaggerInject
import me.militch.quickcore.mvp.model.ModelHelper
import javax.inject.Inject

/**
 * 首页-资讯页面
 * Created by Guojing on 2018/9/4.
 */
class NewsFragment : AbsFragment(), NewsContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var newsPresenter: NewsPresenter
    @Inject
    lateinit var modelHelper: ModelHelper
    private var type: Int = 0// type 0:热门 1:足球 2:中超 3:篮球 4:电竞
    private var titles = arrayOf("热门", "足球", "中超", "篮球", "电竞")
    private var pages = ArrayList<View>()
    private var holders = ArrayList<PageViewHolder>()
    private var loginBean: LoginBean? = null
    private var adapters = ArrayList<NewsMixAdapter>()
    private var pageBeanList = ArrayList<ArrayList<NewsBaseBean>>()
    private var newsBannerBean: NewsBannerBean? = null
    private var newsMatchBean: NewsMatchBean? = null
    private var news = ArrayList<ArrayList<NewsBean>>()

    companion object {
        fun newInstance() = NewsFragment()
    }

    override fun inject(t: ActivityInject?) {
        t!!.inject(this)
    }

    override fun layout(): Int {
        return R.layout.fragment_news
    }

    override fun initView() {
        loginBean = APP.get()!!.loginInfo
        newsPresenter.attachView(this)

        action_goto_feedback.setOnClickListener {
            // 论坛功能实现：https://tucao.qq.com/helper/configLogonState
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title, "论坛交流")
            intent.putExtra(KeyContract.Url, API.LunTan)
            intent.putExtra(KeyContract.EnableRefresh, false)
            startActivity(intent)
        }

        // 初始化页面元素和相应数据以及适配器
        for (i in 1..titles.size) {
            initAdapter()
        }
        initPager()
    }

    private fun initPager() {
        vp_content.adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return pages.size
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                if (pages.size > 0) {
                    container.removeView(pages[position])
                }
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                var view = pages[position]
                var parent = view.parent as? ViewGroup
                parent?.removeAllViews()
                container.addView(view)
                return view
            }
        }
        st_tab.setViewPager(vp_content, titles)
        vp_content.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                type = vp_content.currentItem
                if (news[position].size <= 0) {
                    refreshCurrentPage()
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }


    /**
     * 初始化列表适配器
     */
    private fun initAdapter() {
        // 当前页面的布局
        var pageView = LayoutInflater.from(context).inflate(R.layout.layout_page, vp_content, false) as View
        var holder = PageViewHolder(pageView)

        // 当前页面列表的数据和适配器
        var newsBaseBeanList = ArrayList<NewsBaseBean>()
        var newsBeanList = ArrayList<NewsBean>()
        var newsListAdapter = NewsMixAdapter(context(), this!!.activity!!, newsBaseBeanList)
        holder.rvContent.layoutManager = LinearLayoutManager(context())
        holder.rvContent.adapter = newsListAdapter
        holder.rvContent.addOnItemTouchListener(object : OnItemClickListener() {
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                if ((type == 0 && position >= 2) || type > 0) {
                    var item = if (type == 0) news[0][position - 2] else news[type][position]
                    newsPresenter.newsClick(item.id)
                }
            }
        })
        newsListAdapter.setOnLoadMoreListener({
            if (news[type].size > 0) {
                if (news[type].size % KeyContract.pageSize == 0) {
                    var pageNo = news[type].size / KeyContract.pageSize + 1
                    holders[type].refreshLayout.isEnableRefresh = false
                    newsPresenter.getNewsList(type, pageNo, KeyContract.pageSize)
                } else {
                    adapters[type].loadMoreEnd()
                }
            } else {
                holders[type].refreshLayout.isEnableRefresh = false
                newsPresenter.getNewsList(type, 1, KeyContract.pageSize)
            }
        }, holder.rvContent)
        newsListAdapter.setOnItemChildClickListener { _, view, position ->
            val item = pageBeanList[0][position] as NewsMatchBean
            when (view.id) {
                R.id.action_goto_match1 -> MatchAnalysisActivity.start(context, item.getList()[0].matchId, item.getList()[0].lid)
                R.id.action_goto_match2 -> MatchAnalysisActivity.start(context, item.getList()[1].matchId, item.getList()[1].lid)
            }
        }

        holder.refreshLayout.setOnRefreshListener {
            type = vp_content.currentItem
            refreshCurrentPage()
        }

        // 刷新
        holder.refreshLayout.setOnRefreshListener { refreshCurrentPage() }

        // 将当前的页面、列表控件、数据列表、适配器加入相应的列表
        pages.add(pageView)
        holders.add(holder)
        pageBeanList.add(newsBaseBeanList)
        news.add(newsBeanList)
        adapters.add(newsListAdapter)
    }

    /**
     * 刷新当前页面
     */
    private fun refreshCurrentPage() {
        if (type == 0) {
            newsPresenter.getBannerData()
            newsPresenter.getNewsGames()
        }
        if (loginBean != null) {
            newsPresenter.getWindowList(loginBean!!.userId!!)
        }
        newsPresenter.getNewsList(type, 1, KeyContract.pageSize)

    }

    /**
     * 加载广告
     */
    override fun loadBanner(banner: List<BannerItem>) {
        newsBannerBean = NewsBannerBean(banner)
        adapters[0].notifyDataSetChanged()
    }

    /**
     * 加载比赛
     */
    override fun loadNewsGames(list: List<NewsGameBean>) {
        newsMatchBean = NewsMatchBean(list)
        adapters[0].notifyDataSetChanged()
    }

    /**
     * 加载资讯列表
     */
    override fun loadNewsList(type: Int, pageNo: Int, pageResultBean: PageResultBean<NewsBean>) {
        if (type == 0 && pageNo == 1) {
            pageBeanList[0].clear()
            pageBeanList[0].add(newsBannerBean!!)
            pageBeanList[0].add(newsMatchBean!!)
        }

        if (pageNo == 1) {
            news[type].clear()
            adapters[type].setEnableLoadMore(true)
            if (holders[type].refreshLayout.state.isHeader) {
                holders[type].refreshLayout.finishRefresh()
            }
        }

        if (pageResultBean.records.isNotEmpty()) {
            for (i in 0 until pageResultBean.records.size) {
                pageBeanList[type].add(NewsInfoBean(pageResultBean.records[i]))
            }
            news[type].addAll(pageResultBean.records)
        }

        if (pageResultBean.total > news[type].size) {
            adapters[type].loadMoreComplete()
        } else {
            adapters[type].loadMoreEnd()
        }

        adapters[type].notifyDataSetChanged()
        holders[type].refreshLayout.isEnableRefresh = true
    }

    override fun setWindowList(list: List<WindowBean>) {
        // type 类型 1-中奖；2-邀请首单；3-邀请首冲；4-每日首单；5-新用户注册
        for (i in list.size - 1 downTo 0) {
            when (list[i].type) {
                "1" -> {
                    PrizeDialog(context)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("查看中奖订单") { startActivity(Intent(activity, if (loginBean == null) LoginActivity::class.java else OrderListActivity::class.java)) }
                            .show()
                }
                "6" -> {
                    PrizeDialog(context)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("查看中奖订单") { startActivity(Intent(activity, if (loginBean == null) LoginActivity::class.java else MyPredictionActivity::class.java)) }
                            .show()
                }
                else -> {
                    RewardDialog(context)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("确定")
                            .show()
                }
            }
        }
    }

    override fun newsClickSuccess(newsId: String) {
        val intent = Intent(context, WebViewActivity::class.java)
        intent.putExtra(KeyContract.Title, "资讯详情")
        val url = "${API.newsDetail}?newsId=$newsId"
        intent.putExtra(KeyContract.Url, url)
        context!!.startActivity(intent)
    }

    internal class PageViewHolder(view: View) {
        var rvContent = view.findViewById(R.id.rv_content) as RecyclerView
        var refreshLayout = view.findViewById(R.id.refreshLayout) as SmartRefreshLayout
    }

    override fun onResume() {
        super.onResume()
        refreshCurrentPage()// 加载数据
        UmengAnalyticsHelper.onPageStart("资讯")// 统计页面
        UmengAnalyticsHelper.onResume(context())
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        isHidden.run4false({
            this.onResume()
        }, {
            (holders[type].refreshLayout.state.isFinishing).run4false {
                holders[type].refreshLayout.finishRefresh()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        newsPresenter.detachView()
    }

    override fun onPause() {
        super.onPause()
        UmengAnalyticsHelper.onPageEnd("资讯")// 统计页面
        UmengAnalyticsHelper.onPause(context())
    }
}
